package com.gotop.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gotop.auth.service.IClientService;
import com.gotop.common.enums.EnumStatus;
import com.gotop.common.enums.error.EnumClientError;
import com.gotop.common.exception.BaseException;
import com.gotop.entity.system.Client;
import com.gotop.mapper.system.ClientDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @program: cem
 * @description:
 * @author: superfish
 * @create: 2020-12-30 11:56
 **/
@Service
public class ClientServiceImpl implements IClientService {

    private final ClientDao clientDao;

    public ClientServiceImpl(ClientDao clientDao) {
        this.clientDao = clientDao;
    }

    @Override
    public Client check(String clientId, String clientSecret, String grantType, String ip) {

        final Client client = clientDao.selectOne(
                new QueryWrapper<Client>()
                        .eq("client_id", clientId)
                        .eq("type", 1).last(" limit 1")
        );
        if (null == client) {
            throw new BaseException(EnumClientError.ERROR_CODE1);
        }

        if (client.getStatus() == EnumStatus.FALSE.getCode()) {
            throw new BaseException(EnumClientError.ERROR_CODE6);
        }

        if (!clientSecret.equals(client.getClientSecret())) {
            throw new BaseException(EnumClientError.ERROR_CODE2);
        }

        if (StringUtils.isBlank(client.getIpWhiteList())) {
            throw new BaseException(EnumClientError.ERROR_CODE3);
        }

        if (!client.getIpWhiteList().contains(ip)) {
            throw new BaseException(EnumClientError.ERROR_CODE4);
        }

        if (!client.getAuthorizedGrantTypes().contains(grantType)) {
            throw new BaseException(EnumClientError.ERROR_CODE4);
        }

        return client;
    }

    @Override
    public Client selectByClientId(String clientId_token) {
        final Client client = clientDao.selectOne(
                new QueryWrapper<Client>()
                        .eq("client_id", clientId_token)
                        .eq("type", 1).last(" limit 1")
        );
        if (null == client) {
            throw new BaseException(EnumClientError.ERROR_CODE1);
        }

        if (client.getStatus() == EnumStatus.FALSE.getCode()) {
            throw new BaseException(EnumClientError.ERROR_CODE6);
        }
        return client;
    }
}
